package com.css.fxfzypg.modules.resultupload.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzypg.modules.resultupload.vo.ParamVo;
import com.css.fxfzypg.modules.resultupload.vo.TaskVo;
import com.css.fxfzypg.modules.resultupload.repository.ResultRepository;
import com.css.fxfzypg.modules.resultupload.repository.entity.PrefectureResultEntity;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultEntity;
import com.css.fxfzypg.modules.resultupload.service.ResultService;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
public class ResultServiceImpl implements ResultService {

    @Autowired
    SUserService sUserService;

    @Autowired
    ResultRepository resultRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> uploadPrefectureResult(MultipartFile file, String taskCode) {
        ImportParams params = new ImportParams();
        params.setImportFields(new String[]{"地市、州", "震级", "死亡人数（人）", "受伤人数（人）","需紧急安置人数（人）","需救援力量（人）","需帐篷数量（顶）"});
        params.setNeedVerify(true);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            Date date = new Date();
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<PrefectureResultEntity> result = ExcelImportUtil.importExcelMore(inputStream, PrefectureResultEntity.class, params);
            List<PrefectureResultEntity> resultData = result.getList();//解析excel
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                String cityStr = "";
                List<PrefectureResultEntity> list = new ArrayList<>();
                for(PrefectureResultEntity prefectureResultEntity : resultData){
                    //空行跳过222
                    if(PlatformObjectUtils.isEmpty(prefectureResultEntity.getMagnitude()) && PlatformObjectUtils.isEmpty(prefectureResultEntity.getDeathToll()) && PlatformObjectUtils.isEmpty(prefectureResultEntity.getInjuredNum()) && PlatformObjectUtils.isEmpty(prefectureResultEntity.getResettledNum()) && PlatformObjectUtils.isEmpty(prefectureResultEntity.getRescueForce()) && PlatformObjectUtils.isEmpty(prefectureResultEntity.getTentNum())){
                        continue;
                    }
                    String uuid = UUIDGenerator.getUUID();
                    prefectureResultEntity.setId(uuid);
                    String city = prefectureResultEntity.getCity();
                    if(PlatformObjectUtils.isNotEmpty(city)){
                        cityStr=city;
                    }else{
                        prefectureResultEntity.setCity(cityStr);
                    }
                    prefectureResultEntity.setTaskCode(taskCode);
                    prefectureResultEntity.setDelFlag("0");
                    prefectureResultEntity.setCreateName(userName);
                    prefectureResultEntity.setCreateId(userId);
                    prefectureResultEntity.setCreateTime(date);
                    list.add(prefectureResultEntity);
                }
                if(!PlatformObjectUtils.isEmpty(list)){
                    //获取上传的条数,先删除原先)入的,再进行保存
                    int count = resultRepository.prefectureResultCount(taskCode);
                    if(count > 0){
                        resultRepository.deletePrefectureResult(taskCode);
                    }
                    for(PrefectureResultEntity entity : list){
                        res = resultRepository.savePrefectureResult(entity);//保存
                        if(!res){
                            break;
                        }
                    }
                }

            }
        } catch (Exception e) {
            if (e.getMessage().contains("不是合法")) {
                map.put("mess","上传失败! 上传的文件模板有误,请检查表头是否改动！");
            }
            e.printStackTrace();
        }
        map.put("res",res);
        return map;
    }

    @Override
    public Map<String, Object> getTaskList(TaskVo taskVo, int curPage, int pageSize) {
        String userId = PlatformSessionContext.getUserID();
        return resultRepository.getTaskList(taskVo,userId,curPage,pageSize);
    }

    @Override
    public List<PrefectureResultEntity> getPrefectureResult(String taskCode) {
        return resultRepository.getPrefectureResult(taskCode);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> uploadResult(MultipartFile file, String taskCode) {
        ImportParams params = new ImportParams();
        params.setHeadRows(2);
        params.setNeedVerify(true);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            Date date = new Date();
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            InputStream inputStream = file.getInputStream();
            //解析excel
            ExcelImportResult<ResultEntity> result = ExcelImportUtil.importExcelMore(inputStream, ResultEntity.class, params);
            //校验
            List<ResultEntity> resultList = result.getList();
            if (PlatformObjectUtils.isNotEmpty(resultList)) {
                boolean errorFlag = true;
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (ResultEntity resultEntity : resultList) {
                    //空行跳过
                    if(PlatformObjectUtils.isEmpty(resultEntity.getMagnitude()) && PlatformObjectUtils.isEmpty(resultEntity.getDisasterArea()) && PlatformObjectUtils.isEmpty(resultEntity.getDisasterNum())
                            && PlatformObjectUtils.isEmpty(resultEntity.getDisasterGDP()) && PlatformObjectUtils.isEmpty(resultEntity.getDisasterLoss()) && PlatformObjectUtils.isEmpty(resultEntity.getDeathToll())
                            && PlatformObjectUtils.isEmpty(resultEntity.getInjuredNum()) && PlatformObjectUtils.isEmpty(resultEntity.getResettledNum()) && PlatformObjectUtils.isEmpty(resultEntity.getRescueForce())
                            && PlatformObjectUtils.isEmpty(resultEntity.getTentNum())){
                        continue;
                    }

                    /*if (PlatformObjectUtils.isEmpty(resultEntity.getSort())) {
                        errorFlag=false;
                        errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("序号不能为空!").append("</font>");
                    }
                    if (PlatformObjectUtils.isEmpty(resultEntity.getLongitude())) {
                        errorFlag=false;
                        errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("经度不能为空!").append("</font>");
                    }
                    if (PlatformObjectUtils.isEmpty(resultEntity.getLatitude())) {
                        errorFlag=false;
                        errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("纬度不能为空!").append("</font>");
                    }
                    if (PlatformObjectUtils.isEmpty(resultEntity.getMacroPosition())) {
                        errorFlag=false;
                        errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("宏观位置不能为空!").append("</font>");
                    }*/
                    //校验灾区面积是否为整数
                    BigDecimal disasterArea = resultEntity.getDisasterArea();
                    if(disasterArea !=null){
                        boolean integer = isInteger(disasterArea.toString());
                        if (!integer) {
                            errorFlag=false;
                            errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("灾区面积（km2）应为整数!").append("</font>");
                        }
                    }
                    //校验灾区人口（万人） 校验最大两位小数
                    BigDecimal disasterNum = resultEntity.getDisasterNum();
                    if(disasterNum !=null){
                        if(disasterNum.toString().contains(".")) {
                            String split = disasterNum.toString().split("\\.")[1];
                            if (PlatformObjectUtils.isNotEmpty(split)) {
                                boolean disasterNumRes = split.length() > 2;
                                if (disasterNumRes) {
                                    errorFlag = false;
                                    errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("灾区人口（万人）应小于等于两位小数!").append("</font>");
                                }
                            }
                        }
                    }
                    //校验灾区GDP（亿） 校验最大两位小数
                    BigDecimal disasterGDP = resultEntity.getDisasterGDP();
                    if(disasterGDP !=null){
                        if(disasterGDP.toString().contains(".")) {
                            String split = disasterGDP.toString().split("\\.")[1];
                            if (PlatformObjectUtils.isNotEmpty(split)) {
                                boolean disasterGDPRes = split.length() > 2;
                                if (disasterGDPRes) {
                                    errorFlag = false;
                                    errorMsg.append("<font size='4px'><br>").append("第").append(resultEntity.getRowNum() + 1).append("行： ").append("灾区GDP（亿）应小于等于两位小数!").append("</font>");
                                }
                            }
                        }
                    }
                }
                if(!errorFlag){
                    map.put("res",res);
                    map.put("mess",errorMsg);
                    return map;
                }
            }
            List<ResultEntity> resultData = result.getList();
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                String sortStr = "";
                String longitudeStr = "";
                String latitudeStr = "";
                String macroPositionStr = "";
                List<ResultEntity> list = new ArrayList<>();
                for(ResultEntity resultEntity : resultData){
                    String uuid = UUIDGenerator.getUUID();
                    resultEntity.setId(uuid);
                    String sort = resultEntity.getSort();
                    if(PlatformObjectUtils.isNotEmpty(sort)){
                        sortStr=sort;
                    }else{
                        resultEntity.setSort(sortStr);
                    }
                    String longitude = resultEntity.getLongitude();
                    if(PlatformObjectUtils.isNotEmpty(longitude)){
                        longitudeStr=longitude;
                    }else{
                        resultEntity.setLongitude(longitudeStr);
                    }
                    String latitude = resultEntity.getLatitude();
                    if(PlatformObjectUtils.isNotEmpty(latitude)){
                        latitudeStr=latitude;
                    }else{
                        resultEntity.setLatitude(latitudeStr);
                    }
                    String macroPosition = resultEntity.getMacroPosition();
                    if(PlatformObjectUtils.isNotEmpty(macroPosition)){
                        macroPositionStr=macroPosition;
                    }else{
                        resultEntity.setMacroPosition(macroPositionStr);
                    }
                    resultEntity.setTaskCode(taskCode);
                    resultEntity.setDelFlag("0");
                    resultEntity.setCreateName(userName);
                    resultEntity.setCreateId(userId);
                    resultEntity.setCreateTime(date);
                    list.add(resultEntity);
                }
                if(!PlatformObjectUtils.isEmpty(list)){
                    //获取上传的条数,先删除原先导入的,再进行保存
                    int count = resultRepository.resultCount(taskCode);
                    if(count > 0){
                        resultRepository.deleteResult(taskCode);
                    }
                    for(ResultEntity entity : list){
                        res = resultRepository.saveResult(entity);//保存
                        if(!res){
                            break;
                        }
                    }
                }

            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("res",res);
        return map;
    }

    public static boolean isInteger(String value){
        try{
            Integer.parseInt(value);
            return true;
        }catch (NumberFormatException e){
            return false;
        }

    }

    @Override
    public List<ResultEntity> getResult(String taskCode) {
        List<ParamVo> result = resultRepository.getResult(taskCode);
        List<ResultEntity> resultEntities = new ArrayList<>();
        for(ParamVo paramVo : result){
            List<ResultEntity> list = resultRepository.queryResultData(taskCode,paramVo);
            for(ResultEntity resultEntity : list){
                resultEntity.setRowNum(list.size());
            }
            resultEntities.addAll(list);
        }

        return resultEntities;
    }

    @Override
    public int getPrefectureResultCount(String taskCode) {
        return resultRepository.prefectureResultCount(taskCode);
    }

    @Override
    public int getResultCount(String taskCode) {
        return resultRepository.resultCount(taskCode);
    }

}
